<?php

namespace App\Services\ApplyGoldRecordBatchPay;

use Closure;
use App\Models\User;
use Illuminate\Support\Facades\Redis;
use App\Http\Controllers\Api\V1\Requests\FormRequest;

class ApplyGoldRecordBatchPayRequest extends FormRequest
{
	protected array $unpaidCacheIds = [];

	public function rules(): array
	{
		return [
			'records' => ['array', $this->records()]
		];
	}

	public function records(): Closure
	{
		return function ($key, $value, $fail) {
			/**
			 * @var User $user
			 */
			$user = $this->user();

			$cachedIds = collect($value)->unique();

			if ($cachedIds->count() <= 0) {
				return $fail('请提供正确的抢购记录');
			}

			$needNetMoney = $needCashMoney = big_decimal(0);

			foreach ($cachedIds as $cid) {

				if (! $user->isRecordInUnpaidCache($cid)) {
					return $fail('请提供正确的抢购记录');
				} elseif (! Redis::exists($cid)) {
					return $fail("目标记录不存在:{$cid}");
				} elseif (Redis::hGet($cid, 'is_paying')) {
					return $fail("目标记录已申请付款:{$cid}");
				} elseif (Redis::hGet($cid, 'is_paid')) {
					return $fail("目标记录已付款:{$cid}");
				}

				$needNetMoney = $needNetMoney->plus(Redis::hGet($cid, 'pay_net_price'));
			}

			if (! $user->isGoldCoinsEnough($needNetMoney)) {
				return $fail('账户余额不足');
			}

			$this->unpaidCacheIds = $cachedIds->toArray();

			return true;
		};
	}

	public function getUnpaidCacheIds(): array
	{
		return $this->unpaidCacheIds;
	}
}
